package xmu.crms.service.impl;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import xmu.crms.dao.SeminarGroupDao;
import xmu.crms.dao.UserDAO;
import xmu.crms.entity.School;
import xmu.crms.entity.SeminarGroup;
import xmu.crms.entity.User;
import xmu.crms.exception.ClassesNotFoundException;
import xmu.crms.exception.UserNotFoundException;
import xmu.crms.mapper.UserMapper;
import xmu.crms.service.ClassService;
import xmu.crms.service.SeminarGroupService;
import xmu.crms.service.UploadService;
import xmu.crms.service.UserService;
import xmu.crms.util.ExcelImportUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 *
 * @author badcode
 * @date 2017/12/26
 *
 */
@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private ClassService classService;

    @Autowired
    private SeminarGroupDao seminarGroupDao;

    @Autowired
    private UserService userService;

    private String baseDir = "D:" + System.getProperty("file.separator");

    @Override
    public void uploadReport(SeminarGroup seminarGroup) {
        seminarGroupDao.uploadReport(seminarGroup);
    }

    @Override
    public void uploadStudentList(MultipartFile file, BigInteger classId, BigInteger userId) throws ClassesNotFoundException, UserNotFoundException {
        //判断文件是否为空
        if (file == null) {
            System.out.println("lala");
        }
        String fileName=file.getOriginalFilename();
        System.out.println(fileName);
        String curTime = String.valueOf(System.currentTimeMillis());
        String tempFilename = Base64.getEncoder().encodeToString(curTime.getBytes());
        File tempFile = new File(baseDir + tempFilename);
        System.out.println(tempFile);
        InputStream is = null;
        try {
            //将上传的文件写入新建的文件中
            file.transferTo(tempFile);

            //根据新建的文件实例化输入流
            is = new FileInputStream(tempFile);

            //根据版本选择创建Workbook的方式
            Workbook wb = null;
            //根据文件名判断文件是2003版本还是2007版本
            if (ExcelImportUtils.isExcel2007(fileName)) {
                wb = new XSSFWorkbook(is);
            } else {
                wb = new HSSFWorkbook(is);
            }

            //得到第一个shell
            Sheet sheet=wb.getSheetAt(0);
            //得到Excel的行数
            int totalRows=sheet.getPhysicalNumberOfRows();
            //总列数
            int totalCells = 0;
            //得到Excel的列数(前提是有行数)，从第二行算起
            int num=2;
            if(totalRows>=num && sheet.getRow(1) != null){
                totalCells=sheet.getRow(1).getPhysicalNumberOfCells();
            }
            List<User> studentList=new ArrayList<>();
            School school = new School();
            school.setId(userService.getUserByUserId(userId).getSchool().getId());
            String br = "<br/>";
            String errorMsg = "";

            for(int r=0;r<totalRows;r++) {
                String rowMessage = "";
                Row row = sheet.getRow(r);
                if (row == null){
                    errorMsg += br+"第"+(r+1)+"行数据有问题，请仔细检查！";
                    continue;
                }
                User student = new User();
                student.setSchool(school);
                String number = "";
                String name = "";

                DataFormatter formatter = new DataFormatter();
                for(int c = 0; c <totalCells; c++){
                    Cell cell = row.getCell(c);
                    if (null != cell){
                        if(c==0){
                            number = formatter.formatCellValue(cell);
                            if(StringUtils.isEmpty(number)){
                                rowMessage += "学号不能为空；";
                            } else if (number.length()>20){
                                rowMessage += "学号长度不能大于20";
                            }
                            student.setNumber(number.substring(1));
                        } else if (c==1) {
                            name = number = formatter.formatCellValue(cell);
                            if(StringUtils.isEmpty(name)){
                                rowMessage += "姓名不能为空；";
                            }
                            student.setName(name.substring(1));
                        }
                    } else {
                        rowMessage += "第"+(c+1)+"列数据有问题，请仔细检查；";
                    }
                }
                //拼接每行的错误提示
                if(!StringUtils.isEmpty(rowMessage)){
                    errorMsg += br+"第"+(r+1)+"行，"+rowMessage;
                } else {
                    studentList.add(student);
                }
            }

            //删除上传的临时文件
            if(tempFile.exists()){
                tempFile.delete();
            }

            //全部验证通过才导入到数据库
            if(StringUtils.isEmpty(errorMsg)){
                for(User student : studentList) {
                    User user = userService.getUserByNumber(student.getNumber());
                    if (null == user) {
                        BigInteger studentId = userDAO.insertUser(student);
                        classService.insertCourseSelectionById(studentId, classId);
                    } else {
                        classService.insertCourseSelectionById(user.getId(), classId);
                    }
                }
            }
        } catch (IOException e) {

        }
    }
}
